<template>
  <div class="messages">
    <div v-for="(item, index) in messages" :id="`message_item_${item.MsgID}`" :key="item.MsgID">
      <div class="message-item" :class="{ 'message-item-bot': item.Role === 2 }" v-if="item.MsgType === MessageType.CONTENT_MSG">
        <!-- 发送的loading -->
        <div class="message-item-loading" v-if="item.loading">
          <van-loading type="spinner" size="20px" />
        </div>
        <!-- 发送的消息 -->
        <div class="message-item-content">{{ handleContent(item) }}</div>
        <!-- 心动特效 -->
        <div class="message-item-like" v-if="item.Role === 2 && item.IntimacyDelta && item.IntimacyDelta > 0"></div>
        <!-- 机器人的语音 -->
        <div class="message-item-audio" v-if="item.Role === 2">
          <div class="audio-play" v-if="!audioStatus[index]" @click="createAudioUrl(handleContent(item), index)"></div>
          <div class="audio-playing" v-if="audioStatus[index] === 'play'">
            <div class="line line1"></div>
            <div class="line line2"></div>
            <div class="line line3"></div>
            <div class="line line4"></div>
          </div>
          <div class="audio-loading" v-if="audioStatus[index] === 'loading'">
            <van-loading color="#fff" size="14" />
          </div>
        </div>
      </div>
      <!-- 写真集 -->
      <PhotoAlbum :prizeMsg="item.Content" :aiUserId v-else />
    </div>
    <!-- 机器人回复的loading -->
    <div class="message-loading-main" v-if="status === 'pending'">
      <div class="loading-flashing"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { IMessage, MessageType } from '../../types'
import { getAiChatTts, getTtsContent } from '@/api/chat'
import PhotoAlbum from '../photo-album/index.vue'

const emit = defineEmits(['recommendReplyChange'])
const props = defineProps<{ messages: IMessage[]; status?: string; aiUserId: number }>()
const audioRef = ref<HTMLAudioElement>(document.createElement('audio')) // 创建了一个audio标签
const audioStatus = ref<{ [key: number]: string }>({}) // 存放一下整个列表的播放状态
const audioPlayIndex = ref<number>(0) // 存放一下当前播放的消息index
// 音视频播放
const handleAudioPlay = (url: string) => {
  const audioUrl = `${url}`
  audioRef.value.pause()
  audioRef.value.src = audioUrl
  audioRef.value.load()
}

// 音频开始播放事件
const audioPlay = () => {
  // 音频可以播放
  audioStatus.value[audioPlayIndex.value] = 'play'
  console.log('play')
}

// 音频暂停事件
const audioPause = () => {
  // 音频暂停
  console.log('pause')
}

// 音频结束播放
const audioEnd = () => {
  // 音频结束
  console.log('end')
  audioStatus.value[audioPlayIndex.value] = ''
}

const createAudioUrl = (text: string, index: number) => {
  // 将列表里所有的音频状态重置一下
  Object.keys(audioStatus.value).forEach(item => {
    audioStatus.value[item] = ''
  })
  audioStatus.value[index] = 'loading'
  audioPlayIndex.value = index
  // 页面进入的bot_id
  getAiChatTts(text, props.aiUserId)
    .then(res => {
      getTtsContent(res.url)
        .then(val => {
          if (audioPlayIndex.value !== index) return
          const blob = new Blob([val.data], { type: 'audio/wav' })
          const url = URL.createObjectURL(blob)
          handleAudioPlay(url)
        })
        .catch(console.error)
    })
    .catch(console.error)
}

// 处理消息题
const handleContent = (item: IMessage) => {
  if (item.Role === 1) return item.Content
  if (item.Content.indexOf('{"recommendReply"') > -1) {
    const content = JSON.parse(item.Content)
    emit('recommendReplyChange', content.recommendReply)
    return content.reply
  }
  return item.Content
}

const audioCanPlay = () => {
  console.log('audioCanPlay===audioCanPlay')
  audioRef.value.play()
}

const audioError = error => {
  console.error(error)
}

onMounted(() => {
  audioRef.value.addEventListener('play', audioPlay)
  audioRef.value.addEventListener('pause', audioPause)
  audioRef.value.addEventListener('ended', audioEnd)
  audioRef.value.addEventListener('error', audioError)
  audioRef.value.addEventListener('canplaythrough', audioCanPlay)
})

onUnmounted(() => {
  audioRef.value.removeEventListener('play', audioPlay)
  audioRef.value.removeEventListener('pause', audioPause)
  audioRef.value.removeEventListener('ended', audioEnd)
  audioRef.value.removeEventListener('canplaythrough', audioCanPlay)
  audioRef.value.removeEventListener('error', audioError)
})
</script>

<style scoped lang="scss">
.messages {
  padding: 0 16px;
  .message-item-like {
    height: 46px;
    width: 46px;
    background-image: url('@/assets/images/liked.png');
    background-repeat: no-repeat;
    background-size: 24px 24px;
    background-position: center 46px;
    animation-name: liked;
    animation-duration: 1.2s;
    animation-timing-function: linear;
    opacity: 0;
  }
  .message-loading-main {
    height: 46px;
    background-color: rgba(20, 20, 20, 0.5);
    border-radius: 22px;
    display: flex;
    align-items: center;
    width: 80px;
    justify-content: center;
  }
  .loading-flashing {
    background-color: rgba(106, 69, 255, 1);
    color: rgba(106, 69, 255, 1);
    position: relative;
    left: -9999px;
    width: 10px;
    height: 10px;
    border-radius: 5px;
    box-shadow: 9984px 0 0 0 #9880ff, 9999px 0 0 0 #9880ff, 10014px 0 0 0 #9880ff;
    animation: dotTyping 1.8s infinite linear;
  }
  @keyframes dotTyping {
    0% {
      box-shadow: 9984px 1px 0 0 rgba(106, 69, 255, 1), 9999px -3px 0 0 rgba(190, 182, 252, 1), 10014px -10px 0 0 rgba(190, 182, 252, 1);
    }
    16.667% {
      box-shadow: 9984px -10px 0 0 rgba(190, 182, 252, 1), 9999px -3px 0 0 rgba(106, 69, 255, 1), 10014px 1px 0 0 rgba(190, 182, 252, 1);
    }
    33.333% {
      box-shadow: 9984px -3px 0 0 rgba(190, 182, 252, 1), 9999px -10px 0 0 rgba(190, 182, 252, 1), 10014px -3px 0 0 rgba(106, 69, 255, 1);
    }
    50% {
      box-shadow: 9984px 1px 0 0 rgba(106, 69, 255, 1), 9999px -3px 0 0 rgba(190, 182, 252, 1), 10014px -10px 0 0 rgba(190, 182, 252, 1);
    }
    66.667% {
      box-shadow: 9984px -10px 0 0 rgba(190, 182, 252, 1), 9999px 1px 0 0 rgba(106, 69, 255, 1), 10014px -3px 0 0 rgba(190, 182, 252, 1);
    }
    83.333% {
      box-shadow: 9984px -3px 0 0 rgba(190, 182, 252, 1), 9999px -10px 0 0 rgba(190, 182, 252, 1), 10014px 1px 0 0 rgba(106, 69, 255, 1);
    }
    100% {
      box-shadow: 9984px 1px 0 0 rgba(106, 69, 255, 1), 9999px -3px 0 0 rgba(190, 182, 252, 1), 10014px -10px 0 0 rgba(190, 182, 252, 1);
    }
  }
  .message-item {
    position: relative;
    display: flex;
    justify-content: flex-end;
    margin-bottom: 8px;
    .message-item-loading {
      display: flex;
      align-items: center;
      overflow: hidden;
      height: 48px;
      margin-right: 10px;
    }
    &.message-item-bot {
      margin-top: 24px;
      justify-content: flex-start;
      .message-item-content {
        background-color: rgba(20, 20, 20, 0.5);
        color: rgba(255, 255, 255, 1);
      }
    }
  }
  .message-item-content {
    background-color: rgba(106, 69, 255, 1);
    color: #fff;
    font-family: SF UI Text;
    font-size: 16px;
    font-weight: 400;
    line-height: 24px;
    text-align: left;
    padding: 12px;
    border-radius: 24px;
    word-break: break-all;
    max-width: 228px;
    width: fit-content;
  }
  .message-item-audio {
    position: absolute;
    left: 0;
    top: -14px;
    height: 28px;
    width: 46px;
    background: url('@/assets/images/bot-audio-bg.png') no-repeat center;
    background-size: cover;
    .audio-playing,
    .audio-loading {
      height: 23px;
      width: 46px;
      padding-top: 5px;
      display: flex;
      justify-content: center;
      gap: 2px;
      .line {
        width: 2px;
        height: 12px;
        border-radius: 1px;
        background-color: #fff;
        animation: lineLoading 1.2s infinite ease-in-out;
        &.line2 {
          animation-delay: -1.1s;
        }
        &.line3 {
          animation-delay: -0.2s;
        }
        &.line4 {
          animation-delay: -0.9s;
        }
      }
    }
    .audio-play {
      height: 28px;
      width: 46px;
      background: url('@/assets/images/play.png') no-repeat center 5px;
      background-size: 14px 14px;
    }
  }
  @keyframes lineLoading {
    0%,
    40%,
    100% {
      transform: scaleY(0.4);
    }
    20% {
      transform: scaleY(1);
    }
  }
  @keyframes liked {
    0% {
      opacity: 0;
      background-position: center 46px;
      background-size: 24px 24px;
    }
    30% {
      opacity: 0.6;
      background-position: center 30px;
      background-size: 30px 30px;
    }
    100% {
      opacity: 0.6;
      background-position: center 0px;
      background-size: 30px 30px;
    }
  }
}
</style>
